package org.jeecg.modules.online.cgform.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import java.lang.invoke.SerializedLambda;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
import org.apache.commons.lang.StringUtils;
import org.jeecg.chatgpt.dto.chat.MultiChatMessage;
import org.jeecg.chatgpt.service.AiChatService;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.exception.TuringBootBizTipException;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.modules.online.cgform.consts.ExtendJsonKey;
import org.jeecg.modules.online.cgform.entity.OnlCgformField;
import org.jeecg.modules.online.cgform.entity.OnlCgformHead;
import org.jeecg.modules.online.cgform.enums.CgformConstant;
import org.jeecg.modules.online.cgform.mapper.OnlCgformHeadMapper;
import org.jeecg.modules.online.cgform.model.OnlCgformModel;
import org.jeecg.modules.online.cgform.service.IOnlCgformAiService;
import org.jeecg.modules.online.cgform.service.IOnlCgformHeadService;
import org.jeecg.modules.online.cgform.utils.CgformUtil;
import org.jeecg.modules.online.cgreport.constant.CgReportConstant;
import org.jeecg.modules.online.config.p022d.DataBaseConst;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service("onlineCgformAiServiceImpl")
/* renamed from: org.jeecg.modules.online.cgform.service.a.h */
/* loaded from: hibernate-re-3.7.1-RC.jar:org/jeecg/modules/online/cgform/service/a/h.class */
public class OnlineCgformAiServiceImpl implements IOnlCgformAiService {
    @Autowired
    AiChatService aiChatService;
    @Autowired
    IOnlCgformHeadService onlCgformHeadService;
    @Autowired
    OnlCgformHeadMapper onlCgformHeadMapper;

    /* renamed from: a */
    private static final Logger f459a = LoggerFactory.getLogger(OnlineCgformAiServiceImpl.class);

    /* renamed from: b */
    private static final List<String> f460b = Arrays.asList(CgReportConstant.f494z, "Datetime", "BigDecimal", "Date", DataBaseConst.f579j, "int", CgReportConstant.f496B);

    /* renamed from: c */
    private static final List<String> f461c = Arrays.asList(ExtendJsonKey.f133f, DataBaseConst.f580k, "password", "date", "datetime", "time", "file", "image");

    /* renamed from: a */
//    private static /* synthetic */ Object m178a(SerializedLambda serializedLambda) {
//        String implMethodName = serializedLambda.getImplMethodName();
//        boolean z = true;
//        switch (implMethodName.hashCode()) {
//            case -1998322493:
//                if (implMethodName.equals("getTableName")) {
//                    z = false;
//                    break;
//                }
//                break;
//        }
//        switch (z) {
//            case false:
//                if (serializedLambda.getImplMethodKind() == 5 && serializedLambda.getFunctionalInterfaceClass().equals("com/baomidou/mybatisplus/core/toolkit/support/SFunction") && serializedLambda.getFunctionalInterfaceMethodName().equals("apply") && serializedLambda.getFunctionalInterfaceMethodSignature().equals("(Ljava/lang/Object;)Ljava/lang/Object;") && serializedLambda.getImplClass().equals("org/jeecg/modules/online/cgform/entity/OnlCgformHead") && serializedLambda.getImplMethodSignature().equals("()Ljava/lang/String;")) {
//                    return (v0) -> {
//                        return v0.getTableName();
//                    };
//                }
//                break;
//        }
//        throw new IllegalArgumentException("Invalid lambda deserialization");
//    }

    @Override // org.jeecg.modules.online.cgform.service.IOnlCgformAiService
    public Result<?> genSchema4Modules(String prompt) {
        if (StringUtils.isEmpty(prompt)) {
            return Result.error("请输入提示内容");
        }
        try {
            JSONArray jSONArray = JSONArray.parseObject(m173b(prompt)).getJSONArray("tables");
            if (null != jSONArray && !jSONArray.isEmpty()) {
                List list = (List) f460b.stream().map((v0) -> {
                    return v0.toLowerCase();
                }).collect(Collectors.toList());
                List list2 = (List) f461c.stream().map((v0) -> {
                    return v0.toLowerCase();
                }).collect(Collectors.toList());
                List arrayList = new ArrayList();
                jSONArray.stream().filter(Objects::nonNull).map(obj -> {
                    return (JSONObject) obj;
                }).forEach(jSONObject -> {
                    OnlCgformModel onlCgformModel = new OnlCgformModel();
                    OnlCgformHead m183a = m183a(jSONObject);
                    String tableName = m183a.getTableName();
                    if (null == tableName || tableName.isEmpty()) {
                        return;
                    }
                    m183a.setTableName(m180a(tableName, (Integer) null));
                    onlCgformModel.setHead(m183a);
                    onlCgformModel.setIndexs(Collections.emptyList());
                    onlCgformModel.setDeleteFieldIds(Collections.emptyList());
                    onlCgformModel.setDeleteIndexIds(Collections.emptyList());
                    arrayList.add(onlCgformModel);
                    ArrayList arrayList2 = new ArrayList();
                    onlCgformModel.setFields(arrayList2);
                    AtomicInteger atomicInteger = new AtomicInteger(0);
                    OnlCgformField m179a = m179a("id", "主键", ExtendJsonKey.f133f, "string", true, true, atomicInteger.getAndIncrement());
                    m179a.setDbIsKey(1);
                    arrayList2.add(m179a);
                    arrayList2.add(m179a("create_by", "创建人", ExtendJsonKey.f133f, "string", false, false, atomicInteger.getAndIncrement()));
                    arrayList2.add(m179a("create_time", "创建时间", "datetime", "Datetime", false, false, atomicInteger.getAndIncrement()));
                    arrayList2.add(m179a("update_by", "更新人", ExtendJsonKey.f133f, "string", false, false, atomicInteger.getAndIncrement()));
                    JSONArray fields = jSONObject.getJSONArray("fields");
                    fields.stream().filter(Objects::nonNull).map(obj2 -> {
                        return (JSONObject) obj2;
                    }).forEach(field -> {
                        OnlCgformField onlCgformField = field.toJavaObject(OnlCgformField.class);
                        if (null == onlCgformField.getDbFieldName() || onlCgformField.getDbFieldName().isEmpty() || onlCgformField.getDbFieldName().trim().equalsIgnoreCase("id")) {
                            return;
                        }
                        onlCgformField.setDbFieldName(m181a(onlCgformField.getDbFieldName()));
                        if (null != onlCgformField.getDbType() && !onlCgformField.getDbType().isEmpty() && list.contains(onlCgformField.getDbType().toLowerCase().trim())) {
                            onlCgformField.setDbType(f460b.get(list.indexOf(onlCgformField.getDbType().toLowerCase().trim())));
                        } else {
                            onlCgformField.setDbType(CgReportConstant.f494z);
                        }
                        if (null != onlCgformField.getFieldShowType() && !onlCgformField.getFieldShowType().isEmpty() && list2.contains(onlCgformField.getFieldShowType().toLowerCase().trim())) {
                            onlCgformField.setFieldShowType(f461c.get(list2.indexOf(onlCgformField.getFieldShowType().toLowerCase().trim())));
                        } else {
                            onlCgformField.setFieldShowType(ExtendJsonKey.f133f);
                        }
                        m175a(onlCgformField, atomicInteger.getAndIncrement());
                        arrayList2.add(onlCgformField);
                    });
                });
                IOnlCgformHeadService iOnlCgformHeadService = this.onlCgformHeadService;
                iOnlCgformHeadService.getClass();
                //arrayList.forEach(this::addAll);
            }
            return Result.ok("生成成功");
        } catch (JSONException e) {
            throw new TuringBootBizTipException("ai开小差了,请稍后再试.");
        }
    }

    /* renamed from: a */
    private OnlCgformField m179a(String str, String str2, String str3, String str4, boolean z, boolean z2, int i) {
        OnlCgformField m175a = m175a(new OnlCgformField(), i);
        m175a.setDbFieldName(m181a(str));
        m175a.setDbFieldTxt(str2);
        m175a.setFieldMustInput(z ? "1" : CgformUtil.f304aX);
        m175a.setIsShowForm(0);
        m175a.setIsShowList(0);
        m175a.setIsReadOnly(Integer.valueOf(z2 ? 1 : 0));
        m175a.setFieldShowType(str3);
        m175a.setIsQuery(0);
        m175a.setDbPointLength(0);
        m175a.setDbType(str4);
        m175a.setDbIsNull(Integer.valueOf(z ? 0 : 1));
        return m175a;
    }

    /* renamed from: a */
    private OnlCgformField m175a(OnlCgformField onlCgformField, int i) {
        onlCgformField.setId(UUIDGenerator.generate());
        if (null == onlCgformField.getDbLength()) {
            onlCgformField.setDbLength(50);
        }
        onlCgformField.setFieldLength(120);
        onlCgformField.setQueryConfigFlag(CgformUtil.f304aX);
        onlCgformField.setQueryMode("single");
        onlCgformField.setOrderNum(Integer.valueOf(i));
        onlCgformField.setIsReadOnly(0);
        onlCgformField.setIsShowForm(1);
        onlCgformField.setIsShowList(1);
        onlCgformField.setDbIsNull(1);
        onlCgformField.setDbIsKey(0);
        return onlCgformField;
    }

    /* renamed from: a */
    public static String m181a(String str) {
        if (str.length() < 3) {
            return str.toLowerCase();
        }
        StringBuilder sb = new StringBuilder(str);
        int i = 0;
        for (int i2 = 2; i2 < str.length(); i2++) {
            if (Character.isUpperCase(str.charAt(i2))) {
                sb.insert(i2 + i, "_");
                i++;
            }
        }
        return sb.toString().toLowerCase();
    }

    /* renamed from: a */
    private OnlCgformHead m183a(JSONObject jSONObject) {
        OnlCgformHead onlCgformHead = new OnlCgformHead();
        onlCgformHead.setTableName(jSONObject.getString("tableName"));
        onlCgformHead.setTableName(m181a(onlCgformHead.getTableName()));
        onlCgformHead.setTableTxt(jSONObject.getString("tableTxt"));
        onlCgformHead.setTableVersion(1);
        onlCgformHead.setTableType(CgformConstant.f369d);
        onlCgformHead.setFormCategory("temp");
        onlCgformHead.setIdType("UUID");
        onlCgformHead.setIsCheckbox("Y");
        onlCgformHead.setThemeTemplate(CgformUtil.f239K);
        onlCgformHead.setFormTemplate("1");
        onlCgformHead.setScroll(1);
        onlCgformHead.setIsPage("Y");
        onlCgformHead.setIsTree("N");
        onlCgformHead.setExtConfigJson("{\"reportPrintShow\":0,\"reportPrintUrl\":\"\",\"joinQuery\":0,\"modelFullscreen\":0,\"modalMinWidth\":\"\",\"commentStatus\":0,\"tableFixedAction\":1,\"tableFixedActionType\":\"right\"}");
        onlCgformHead.setIsDesForm("N");
        onlCgformHead.setDesFormCode("");
        return onlCgformHead;
    }

    /* renamed from: a */
    private String m180a(String str, Integer num) {
        Integer num2;
        if (null == num || num.intValue() < 0) {
            num2 = 0;
        } else {
            num2 = Integer.valueOf(num.intValue() + 1);
            str = str + "_" + num2;
        }
        if (null == str || str.isEmpty()) {
            return "ai_table_" + System.currentTimeMillis();
        }
        if (this.onlCgformHeadMapper.exists(Wrappers.lambdaQuery(OnlCgformHead.class).eq(OnlCgformHead::getTableName, str))) {
            return m180a(str, num2);
        }
        return str;
    }

    /* renamed from: b */
    private String m173b(String str) {
        LinkedList linkedList = new LinkedList();
        linkedList.add(MultiChatMessage.builder().role(MultiChatMessage.Role.SYSTEM).content("你会根据业务需求设计与需求相关的表单；只输出json数据不要有其他描述。").build());
        linkedList.add(MultiChatMessage.builder().role(MultiChatMessage.Role.USER).content("输出一个json对象，该对象由表集合（tables)和字典数据（dictData）组成。表集合是一个数组，每个表是一个json对象，属性包含：中文名（tableTxt)、英文名(tableName)、字段列表(fields);字典数据是一个json对象，比如：{\"字典编码\":[{\"value\":\"字典值\",\"text\":\"展示值\"}]};字段列表是一个json数组，包含字段英文名(dbFieldName)、字段中文名(dbFieldTxt)、字段数据库类型(dbType)、字段数据库类型长度(dbLength),字段数据库小数类型长度(dbPointLength)、字段显示类型(fieldShowType)、字段是否必填(fieldMustInput)、字段是否查询字段(isQuery)。字段英文名和表英文名使用下划线命名法(UnderScoreCase);不要生成当前表的主键字段或ID字段;可用的字段数据库类型(dbType)包含：String、Datetime、BigDecimal、Date、Text、int、Double。可用的字段显示类型(fieldShowType)包含：text、textarea、password、date、datetime、time、file、image。字段数据库类型(dbType)和字段显示类型(fieldShowType)只能使用上述选项。密码的显示类型是:password参考json：{\"tables\":[{\"tableName\":\"order\",\"tableTxt\":\"订单表\",\"fields\":[{\"dbFieldName\":\"name\",\"dbFieldTxt\":\"姓名\",\"dbType\":\"string\",\"dbLength\":20,\"dbPointLength\":0,\"fieldShowType\":\"input\",\"fieldMustInput\":\"1\",\"isQuery\":0}]}]}。").build());
        linkedList.add(MultiChatMessage.builder().role(MultiChatMessage.Role.USER).content("业务需求如下:" + str).build());
        String multiCompletions = this.aiChatService.multiCompletions(linkedList);
        if (StringUtils.isEmpty(multiCompletions)) {
            throw new TuringBootBizTipException("如果您想使用AI助手，请先设置相应配置!");
        }
        f459a.debug("ai返回结果" + multiCompletions);
        Matcher matcher = Pattern.compile("\\{.*}", 32).matcher(multiCompletions);
        String str2 = "";
        if (matcher.find()) {
            str2 = matcher.group(0);
        }
        return str2;
    }
}
